package GameDb.Task;

import GameDb.JDBC.JDBCTemplate;
import GameDb.Task.common.DbTask;
import Protobuf.DbProto;
import io.netty.channel.ChannelHandlerContext;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

public class SendPrivateChat implements DbTask {

    private final ChannelHandlerContext ctx;
    private final long id;
    private final String clientChannelId;

    public SendPrivateChat(ChannelHandlerContext ctx,long id,String channelId){
        this.ctx = ctx;
        this.id = id;
        this.clientChannelId = channelId;
    }

    @Override
    public void run(Connection conn) throws Exception {
        String sql = "SELECT b.message,b.time,b.receiver_id,a.name,b.suc FROM private_chat b INNER JOIN player a ON b.sender_id=a.id  WHERE b.receiver_id =?";
        JDBCTemplate jdbcTemplate = new JDBCTemplate();
        List<Map<String,Object>> list =(List<Map<String,Object>>)jdbcTemplate.selectDbOperate(conn,sql,4,id);
        for(Map<String,Object> map:list){
            DbProto.Msg chat = DbProto.Msg.newBuilder().setMsgType(DbProto.Msg.MsgType.priChat)
                    .setChannelId(clientChannelId).setChatMsg(DbProto.ChatMsg.newBuilder()
                            .setSenderName((String)map.get("name"))
                            .setMsg((String)map.get("message"))
                            .setTime(String.valueOf(map.get("time")))
                            .setReceiverId((Long)map.get("receiver_id"))
                            .setSendSuc((int)map.get("suc")).build())
                    .build();
            ctx.writeAndFlush(chat);
        }
    }

}
